import TableHeader from "../Table/TableHeader";
import TodoHeader from "./TodoHeader";
import TodoContainer from "./TodoContainer";
import {useReducer} from "react";

let nextId = 1
const todoData = [
    {
        id:0,
        todoMsg:'尝试添加todo',
        isDone:false
    }
]

const todoReducer = (state,action)=>{
    switch (action.type) {
        case 'add_todo':
           return [
               ...state,
               {id:nextId++,todoMsg:action.todoMsg,isDone:false}
           ]
        case 'change_state_todo':
            return state.map(item=>{
                if(item.id === action.id) {
                    return {...item,isDone: !item.isDone}
                }
                return item
            })
        case 'delete_todo':
            return state.filter(item=>item.id!==action.id)
        case 'edit_todo':
            return state.map(item=>{
                if(item.id === action.id) {
                    return {...item,todoMsg: action.todoMsg}
                }
                return item
            })
        default:
            throw Error(`未知action：${action.type}`)
    }
}
const TodoList = ()=>{
    const [state,dispatch] = useReducer(todoReducer,todoData)

    const doneList = state.filter(item=>item.isDone)
    const notDoneList  = state.filter(item=>!item.isDone)
    return (
        <>
            <div className='small-container flex-small'>
                <TodoHeader {...{dispatch}}/>
            </div>
            <div className='small-container flex-small'>
                <h2>未完成</h2>
                <TodoContainer {...{list:notDoneList,dispatch}}/>
                <hr/>
            </div>
            <div className='small-container flex-small'>
                <h2>已完成</h2>
                <TodoContainer {...{list:doneList,dispatch}}/>
            </div>
        </>
    )
}

export default TodoList